package com.bjpower.utils.kuaiqianutils;

import org.apache.commons.codec.binary.Base64;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Pkipair {
    public String signMsg(String signMsg,String merchPrivateFile) {

        String base64 = "";
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12");

            //商户私钥文件 , 不同的商家 有自己的私钥文件
            String file = Pkipair.class.getResource(merchPrivateFile).getPath().replaceAll("%20", " ");
            System.out.println(file);

            FileInputStream ksfis = new FileInputStream(file);
            BufferedInputStream ksbufin = new BufferedInputStream(ksfis);

            //密码
            char[] keyPwd = "123456".toCharArray();
            ks.load(ksbufin, keyPwd);

            //别名
            PrivateKey priK = (PrivateKey) ks.getKey("20240619.3300000010258522", keyPwd);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priK);
            signature.update(signMsg.getBytes("utf-8"));
            //sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            //base64 = encoder.encode(signature.sign());
            //编码
            Base64 encode = new Base64();

            //base64转码后的签名值 signMsg
            base64 =  encode.encodeAsString(signature.sign());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return base64;
    }

    //验证签名。 需要使用快钱的公钥
    public boolean enCodeByCer(String val, String msg) {
        boolean flag = false;
        try {

            //读取快钱公钥
            String file = Pkipair.class.getResource("sandbox.publicKey.cer").toURI().getPath();
            System.out.println(file);
            FileInputStream inStream = new FileInputStream(file);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

            PublicKey pk = cert.getPublicKey();

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(pk);
            signature.update(val.getBytes());

            //sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            //flag = signature.verify(decoder.decodeBuffer(msg));

            //解码
            Base64 decoder = new Base64();
            flag = signature.verify(decoder.decode(msg.getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

}
